import Vue from 'vue'
import router from './router'
import store from './store'
import { ACCESS_TOKEN } from "@/store/mutation_types";
import { generateIndexRouter } from "@/utils/router";
const whiteList = ['/']
router.beforeEach((to, from, next) => {
  // 是否有token
  if (Vue.ls.get(ACCESS_TOKEN)) {
    if (whiteList.indexOf(to.path) !== -1) {
      //判断跳转的路径格式是否正确
      const rediect = decodeURIComponent(to.path);
      if (to.path == rediect) {
        next()
      } else {
        next({ path: rediect })
      }
    } else {
      // if(store.)
      // 是否有菜单值
      if (store.state.user.permissions.length == 0) {
        store.dispatch('getMenuList').then(res => {
          const menuData = res.data;
          if (menuData.length == 0) {
            return;
          }
          let constRoutes = generateIndexRouter(menuData)
          // 添加主界面路由
          store.dispatch('UpdateAppRouter', { constRoutes }).then(() => {
            const promiseList = store.state.permission.addRouters;
            promiseList.forEach(item => {
              router.addRoute(item);
            });
            // router.addRoutes(store.state.permission.addRouters)
            const redirect = decodeURIComponent(from.query.redirect || to.path)
            if (to.path === redirect) {
              next({ ...to, replace: true })
            } else {
              next({ path: redirect })
            }
          })
        })
      } else {
        next()
      }
    }

  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      next({ path: '/' })
    }
  }
})
